<template>
  <el-dialog v-model="foodStore.foodMaterialDialog.visible"
             :title="foodStore.foodMaterialDialog.title"
             center @open="openDialogEvent"
             class="food-material-dialog">
    <el-form ref="formRef" :model="foodStore.foodMaterialDialog.data"
             :rules="rules">
      <el-form-item label="类型" prop="type">
        <el-select
            v-model="foodStore.foodMaterialDialog.data.type"
            placeholder="请选择类型">
          <el-option
              v-for="(item, index) in foodMaterialTypeList"
              :key="index" :label="item" :value="item"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="名称" prop="name">
        <el-input v-model="foodStore.foodMaterialDialog.data.name" autocomplete="off"
                  placeholder="请输入名称" clearable
                  show-word-limit maxlength="20">
        </el-input>
      </el-form-item>

      <el-form-item label="分量" prop="amount">
        <el-input v-model="foodStore.foodMaterialDialog.data.amount" autocomplete="off"
                  placeholder="请输入分量（1斤/2勺/适量）" clearable
                  show-word-limit maxlength="20">
        </el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancelClick">取消</el-button>
        <el-button type="primary" @click="confirmClick">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { useFoodStore } from '@/store/food.ts'
import { nextTick, reactive, ref } from 'vue'
import { FormRules } from 'element-plus'
import { foodMaterialRules } from '@/utils/element/elRules.ts'
const rules = reactive<FormRules>(foodMaterialRules)

const formRef = ref()
const foodStore = useFoodStore()

const foodMaterialTypeList = ['主料', '辅料', '调料']

/**
 * 打开对话框事件
 */
const openDialogEvent = () => {
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

/**
 * 点击确认按钮
 */
const confirmClick = () => {
  formRef.value.validate().then(async () => {
    if (foodStore.foodMaterialApiType === 'UPDATE') {
      const { editFoodMaterialIndex: index } = foodStore
      foodStore.foodRecipeDialog.data.materialList[index] = foodStore.foodMaterialDialog.data
    } else {
      foodStore.foodRecipeDialog.data.materialList.push(foodStore.foodMaterialDialog.data)
    }
    foodStore.foodMaterialDialog.visible = false
  })
}

const cancelClick = () => {
  foodStore.foodMaterialDialog.visible = false
}
</script>

<style lang="scss">
.food-material-dialog {
  width: 30%;

  .el-dialog__body {
    // height: 50vh;
  }
}
</style>
